
package com.casstime.ec.cloud.discount.jms;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import com.casstime.commons.utils.IncrementIdCreator;
import com.casstime.commons.utils.JsonUtil;
import com.casstime.ec.cloud.clients.feign.order.OrderClient;
import com.casstime.ec.cloud.discount.dao.amount.AmountPromotionConfigAmountMapper;
import com.casstime.ec.cloud.discount.dao.amount.AmountPromotionFlowingMapper;
import com.casstime.ec.cloud.discount.dao.business.SupplierGarageBusinessMapper;
import com.casstime.ec.cloud.discount.services.DiscountDAOService;
import com.casstime.ec.cloud.values.amountPromotion.AmountPromotionConfigAmount;
import com.casstime.ec.cloud.values.amountPromotion.AmountPromotionFlowing;
import com.casstime.ec.cloud.values.business.SupplierGarageBusiness;
import com.casstime.ec.cloud.values.order.query.OrderedProductStore;
import com.google.common.collect.Lists;
/**
 * 
 * ClassName: OrderMessageListener 
 * Function: (促销活动监控订单消息插入订单流水)
 * Reason: ADD REASON(可选).
 *  
 * @author hongcheng.wu  
 * 2018年1月8日 下午8:43:52
 * @version   
 * @since JDK 1.8
 */
@Component
public class OrderMessageListener {
	 private Logger logger = LoggerFactory.getLogger(OrderMessageListener.class);
	
	 @Autowired
	 private AmountPromotionConfigAmountMapper amountPromotionConfigAmountMapper;	
	 
	 @Autowired
	 private AmountPromotionFlowingMapper amountPromotionFlowingMapper;
	 
	 @Autowired
	 private SupplierGarageBusinessMapper supplierGarageBusinessMapper;
	 
	 @Autowired
	 private OrderClient orderClient;
	 
	 @Autowired
	 private DiscountDAOService discountDAOService;
	 
	@SuppressWarnings("unchecked")
	@JmsListener(destination = "${spring.activemq.queue.submit}")
	public void queueHandleMessage(String message) {
		logger.info("促销订单推送信息: {}", message);
		String orderId = null; //订单id
		String orderStatusId = null;
		Date orderDate = null; //下单时间
		String companyId = null; //维修厂公司id
		String companyName = null; //维修厂名称
		String userId = null; //用户id
		String configId = null; //满减配置id
		String promotionId = null; //满减活动id
		BigDecimal amountPrice = BigDecimal.ZERO; //满减总金额
		BigDecimal totalAmount = BigDecimal.ZERO; //订单总金额
		List<Map<String, Object>> orderItems = Lists.newArrayList(); //订单商品item
		List<AmountPromotionFlowing> flowList = Lists.newArrayList();
		List<String> configIds = Lists.newArrayList();
		if (message == null || StringUtils.isEmpty(message)) {
			logger.warn("促销订单推送信息为空: {}", message);
		} else {
			Map<String, Object> orderMap = JsonUtil.deserialize(message);
			if (Integer.parseInt(orderMap.get("retryTime").toString()) == 0) {
				try {
					Map<String, Object> orderHeader = (Map<String, Object>) orderMap.get("orderHeader");
					orderId = (String) orderHeader.get("orderId");
					orderStatusId = (String) orderHeader.get("statusId");
					String orderDateStr = (String) orderHeader.get("createDate");
				    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    orderDate  = format.parse(orderDateStr); 
				    Map<String, Object> orderUser = (Map<String, Object>) orderMap.get("user");
				    companyId = (String) orderUser.get("companyId");
				    companyName = (String) orderUser.get("companyName");
				    userId = (String) orderUser.get("userId");
				    if (orderMap.containsKey("orderItems") && null != orderMap.get("orderItems")) {
						orderItems = (List<Map<String, Object>>) orderMap.get("orderItems");
					}
				} catch (Exception e) {
					logger.error("转换订单详情失败", e);
				}
			}
			if (StringUtils.isNotEmpty(orderId)
					&& "ORDER_WAIT_PAYED".equals(orderStatusId)
					&& CollectionUtils.isNotEmpty(orderItems)) {
					for (Map<String, Object> orderItem : orderItems) {
			    	double unitPrice = Double.parseDouble(orderItem.get("price").toString());
			    	double quantity = Double.parseDouble(orderItem.get("quantity").toString());
			    	totalAmount = totalAmount.add(BigDecimal.valueOf(unitPrice).multiply(BigDecimal.valueOf(quantity)));
			    	if (orderItem.containsKey("adjustments") && null != orderItem.get("adjustments")) {
			    	 List<Map<String, Object>> adjustMentList = (List<Map<String, Object>>) orderItem.get("adjustments");
			    	 for (Map<String, Object> adjustMent : adjustMentList) {
			    	 		//店铺满减
			    	 		if ("STORE_PROMOTION_FULLOFF".equals(adjustMent.get("adjustmentType").toString())) {
			    	 			configId =  String.valueOf(adjustMent.get("objectType"));
			    	 			promotionId = String.valueOf(adjustMent.get("objectId"));
			    	 			double price = Double.parseDouble(String.valueOf(adjustMent.get("buyyerAdjustment")));
			    	 			amountPrice = amountPrice.add(BigDecimal.valueOf(price).multiply(BigDecimal.valueOf(quantity)));
			    	 		}
			    	 	}
			    	 }
				   }
				}
				if (StringUtils.isNotEmpty(promotionId) && StringUtils.isNotEmpty(configId) 
						&& amountPrice.compareTo(BigDecimal.ZERO) > 0) {
					 IncrementIdCreator idCreator = new IncrementIdCreator();
					 AmountPromotionFlowing amountPromotionFlowing = new AmountPromotionFlowing();
		 			 amountPromotionFlowing.setCompanyId(companyId);
		 			 amountPromotionFlowing.setCompanyName(companyName);
		 			 amountPromotionFlowing.setId(idCreator.getNextIncrementId());
		 			 amountPromotionFlowing.setOrderAmount(String.valueOf(totalAmount));
		 			 amountPromotionFlowing.setConfigId(configId);
		 			 amountPromotionFlowing.setPromotionId(promotionId);
		 			 amountPromotionFlowing.setOrderId(orderId);
		 			 amountPromotionFlowing.setOrderTime(orderDate);
		 			 amountPromotionFlowing.setAmountCut(String.valueOf(amountPrice));
		 			 List<SupplierGarageBusiness> bussinessList = supplierGarageBusinessMapper.listSupplierGarageBusiness(companyId);
		 			if (CollectionUtils.isEmpty(bussinessList)) {
		 				amountPromotionFlowing.setFirstOrder("Y");
		 			}
		 			flowList.add(amountPromotionFlowing);
		 			configIds.add(configId);
		 			discountDAOService.addAmountPromotionAmount(promotionId, amountPrice);
				}
				List<AmountPromotionConfigAmount> amountList = Lists.newArrayList();
				if (CollectionUtils.isNotEmpty(configIds)) {
					amountList = amountPromotionConfigAmountMapper.findConfigAmountByConfigIds(configIds);
				}
				if (CollectionUtils.isNotEmpty(flowList) && CollectionUtils.isNotEmpty(amountList)) {
					for (AmountPromotionFlowing flow : flowList) {
						for (AmountPromotionConfigAmount amount : amountList) {
							if (flow.getConfigId().equals(amount.getId())) {
								flow.setAmountCutRequire(amount.getRequireAmount());
							}
						}
					}
					amountPromotionFlowingMapper.insertAmountPromotionFlowing(flowList);
				}
				//查询最近读取交易的店铺列表
				List<OrderedProductStore> stores = orderClient.getRecentlyOrderedProductStores(userId,
					companyId, null);
				List<SupplierGarageBusiness> records = Lists.newArrayList();
				for (OrderedProductStore store : stores) {
					SupplierGarageBusiness supplierGarageBusiness = new SupplierGarageBusiness();
    	 			supplierGarageBusiness.setGarageCompanyId(companyId);
    	 			supplierGarageBusiness.setProductStoreId(store.getProductStoreId());
    	 			supplierGarageBusiness.setCreatedDate(new Date());
    	 			records.add(supplierGarageBusiness);
				}
				if (CollectionUtils.isNotEmpty(records)) {
					supplierGarageBusinessMapper.insertSupplierGarageBusiness(records);
				}
			}
			
	}
}
	
	


